package com.security.handler;

import com.security.model.RequestLog;
import com.security.service.RequestLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.LocalDateTime;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private final RequestLogService requestLogService;

    public CustomAccessDeniedHandler(RequestLogService requestLogService) {
        this.requestLogService = requestLogService;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        // 记录被拦截的请求信息
        RequestLog log = new RequestLog();
        log.setMethod(request.getMethod());
        log.setUrl(request.getRequestURI());
        log.setQueryString(request.getQueryString());
        log.setRemoteAddr(request.getRemoteAddr());
        log.setUserAgent(request.getHeader("User-Agent"));
        log.setAccessTime(LocalDateTime.now());
        log.setDeniedReason("AUTH_REQUIRED"); // 认证失败
        
        // 异步保存到数据库
        requestLogService.logRequest(log);

        // 返回错误响应
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write("{\"error\":\"Access Denied\",\"message\":\"Authentication required\"}");
    }
}